package com.lanou.moving.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.moving.R;
import com.lanou.moving.adapter.SongListDetailAdapter;
import com.lanou.moving.base.BaseActivity;
import com.lanou.moving.base.BaseApplication;
import com.lanou.moving.constant.URL;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.entity.SongListDetail;
import com.lanou.moving.entity.dao.AddTo;
import com.lanou.moving.entity.dao.AddToDao;
import com.lanou.moving.entity.dao.Collection;
import com.lanou.moving.entity.dao.CollectionDao;
import com.lanou.moving.entity.dao.RecentlyPlay;
import com.lanou.moving.entity.dao.RecentlyPlayDao;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.service.DownloadServices;
import com.lanou.moving.singleton.DaoSingleton;
import com.lanou.moving.view.CDSPopupWindow;
import com.lanou.moving.volley.StringRequestUtf;
import com.lanou.moving.volley.VolleySingleton;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by 刘琪 on 15/10/28.
 */

public class SongListDetailActivity extends BaseActivity implements View.OnClickListener,
        AdapterView.OnItemClickListener, SongListDetailAdapter.OnMenuClickListener {

    private CollapsingToolbarLayout toolbarLayout;
    private VolleySingleton volleySingleton;
    private StringRequestUtf request;
    private List<SongListDetail.SongsEntity> songsEntities;
    private SongListDetail.ImageEntity imageEntities;
    private int id;
    private ImageView songs_list_bg;
    private SongListDetailAdapter adapter;
    private ListView songs_list_listview;
    private Toolbar coordinator_toolbar;
    private List<MusicInfo> musicInfoList;
    private TextView songs_list_collection;
    private SongListDetail songList;

    //数据库表
    private AddToDao addToDao;
    private CollectionDao collectionDao;
    private RecentlyPlayDao recentlyPlayDao;
    private View view;
    private TextView collect_tv, share_tv;
    private ImageView rankingListBackground;
    private List<Collection> collections;
    private CDSPopupWindow pw;

    private String url;


    final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");


    private int index = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ranking_list_detail);
        BaseApplication.getInstance().addActivity(this);
        volleySingleton = VolleySingleton.getInstance(this);
        addToDao = DaoSingleton.getInstance().getAddToDao();
        collectionDao = DaoSingleton.getInstance().getCollectionDao();
        recentlyPlayDao = DaoSingleton.getInstance().getRecentlyPlayDao();

        view = LayoutInflater.from(this).inflate(R.layout.layout_song, null);
        collect_tv = (TextView) view.findViewById(R.id.layout_song_collection);
        share_tv = (TextView) view.findViewById(R.id.layout_song_share);

        songs_list_bg = (ImageView) findViewById(R.id.songs_list_bg);
        toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);

        coordinator_toolbar = (Toolbar) findViewById(R.id.coordinator_toolbar);


        initShare();
        QQShare();

        coordinator_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        songs_list_listview = (ListView) findViewById(R.id.songs_list_listview);
        songs_list_listview.setOnItemClickListener(this);

        songs_list_collection = (TextView) findViewById(R.id.songs_list_collection);
        songs_list_collection.setOnClickListener(this);

        rankingListBackground = (ImageView) findViewById(R.id.new_song_background);
        Intent intent = getIntent();
        id = intent.getIntExtra("id", 0);
        getData();
    }

    public void getData() {
        String url = URL.SONG_LIST_DETAIL_START + id + URL.SONG_LIST_DETAIL_END;
        request = new StringRequestUtf(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                songList = gson.fromJson(response, SongListDetail.class);
                toolbarLayout.setTitle(songList.getTitle());
                songsEntities = songList.getSongs();
                imageEntities = songList.getImage();
                Picasso.with(SongListDetailActivity.this).load(imageEntities.getPic())
                        .placeholder(R.mipmap.songlist_cover).error(R.mipmap.songlist_cover).into(songs_list_bg);
                adapter = new SongListDetailAdapter(SongListDetailActivity.this, songsEntities);
                adapter.setOnMenuClickListener(SongListDetailActivity.this);
                songs_list_listview.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request);
    }

    @Override
    protected void onResume() {
        super.onResume();
        List<AddTo> lists = addToDao.queryBuilder().where(AddToDao.Properties.SongListId.eq(id)).list();
        if (lists != null && lists.size() > 0) {
            songs_list_collection.setText("取消收藏");
        } else {
            songs_list_collection.setText("收藏");
        }
    }

    private void initShare() {
        UMQQSsoHandler umqqSsoHandler = new UMQQSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        umqqSsoHandler.addToSocialSDK();
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
    }

    private void QQShare() {
        QQShareContent qqShareContent = new QQShareContent();
        //设置分享文字
        qqShareContent.setShareContent("第一次分享东西， 好好看");
        //设置分享title
        qqShareContent.setTitle("哈哈哈");
        //设置点击分享内容的跳转连接
        qqShareContent.setTargetUrl(url);
        //????
        mController.setShareMedia(qqShareContent);
        QZoneShareContent qzone = new QZoneShareContent();
        //设置分享文字
        qzone.setShareContent("第一次给你分享东西，好好看");
        //设置分享内容的标题
        qzone.setTitle("哈哈哈");
        //设置点击消息的跳转URL
        qzone.setTargetUrl(url);
        mController.setShareMedia(qzone);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.songs_list_collection:
                if ("收藏".equals(songs_list_collection.getText())) {
                    AddTo addTo = new AddTo();
                    addTo.setName(songList.getTitle());
                    addTo.setSongListId(id);
                    addTo.setPicUrl(songList.getImage().getPic());
                    addTo.setSongs(songList.getSongs().size());
                    addTo.setResource("歌单");
                    addToDao.insert(addTo);
                    songs_list_collection.setText("取消收藏");
                    Toast.makeText(this, "已加入收藏", Toast.LENGTH_LONG).show();
                } else if ("取消收藏".equals(songs_list_collection.getText())) {
                    addToDao.queryBuilder().where(AddToDao.Properties.SongListId.eq(id)).buildDelete()
                            .executeDeleteWithoutDetachingEntities();
                    songs_list_collection.setText("收藏");
                    Toast.makeText(SongListDetailActivity.this, "已取消收藏", Toast.LENGTH_LONG).show();
                }
                break;

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        SongListDetail.SongsEntity songsEntity = (SongListDetail.SongsEntity) parent.getItemAtPosition(position);
        if ((songsEntity.getUrlList() != null && songsEntity.getUrlList().size() > 0)) {
            RecentlyPlay recentlyPlay = new RecentlyPlay();
            recentlyPlay.setSongName(songsEntity.getName());
            recentlyPlay.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
            recentlyPlay.setDuration(songsEntity.getUrlList().get(0).getDuration());
            recentlyPlay.setSingerName(songsEntity.getSingerName());
            recentlyPlay.setSongId((long) songsEntity.getSongId());
            recentlyPlay.setResource("网络");
            recentlyPlayDao.insertOrReplace(recentlyPlay);

            EventBus.getDefault().post(new MyEventBus.PlayMusic(1));
            musicInfoList = new ArrayList<>();

            for (SongListDetail.SongsEntity entity : songsEntities) {
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setAlbumId((int) entity.getAlbumId());
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setResouce("网络");
                    musicInfoList.add(musicInfo);
                }
            }

            Intent intent = new Intent(SongListDetailActivity.this, PlayMusicActivity.class);
            EventBus.getDefault().post(new MyEventBus.Deliver(musicInfoList, songsEntity.getName()));
            intent.putExtra("songName", songsEntity.getName());
            intent.putExtra("duration", songsEntity.getUrlList().get(0).getDuration());
            intent.putExtra("resource", "网络");
            intent.putExtra("albumId", songsEntity.getAlbumId());
            intent.putExtra("singerName", songsEntity.getSingerName());
            startActivity(intent);
        } else {
            Toast.makeText(this, "暂时无法播放此歌曲", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onMenuClick(final SongListDetail.SongsEntity songsEntity) {
        rankingListBackground.setVisibility(View.VISIBLE);
        collections = collectionDao.queryBuilder().where(
                CollectionDao.Properties.SongId.eq(songsEntity.getSongId())).list();
        if (collections != null && collections.size() > 0) {
            collect_tv.setText("取消收藏");
        } else {
            collect_tv.setText("收藏");
        }
        pw = new CDSPopupWindow(this, view, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.layout_song_collection:
                        if ("收藏".equals(collect_tv.getText())) {
                            Collection collection = new Collection();
                            collection.setSongId(songsEntity.getSongId());
                            collection.setSongName(songsEntity.getName());
                            collection.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
                            collection.setAlbumId((int) songsEntity.getAlbumId());
                            collection.setDuration(songsEntity.getUrlList().get(0).getDuration());
                            collection.setSingerName(songsEntity.getSingerName());
                            collectionDao.insert(collection);
                            collect_tv.setText("取消收藏");
                            Toast.makeText(SongListDetailActivity.this, "已收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        } else if ("取消收藏".equals(collect_tv.getText())) {
                            collectionDao.queryBuilder().where(CollectionDao.Properties.SongId
                                    .eq(songsEntity.getSongId())).buildDelete()
                                    .executeDeleteWithoutDetachingEntities();
                            collect_tv.setText("收藏");
                            Toast.makeText(SongListDetailActivity.this, "已取消收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        }
                        break;
                    case R.id.layout_song_download:
                        if (songsEntity.getAuditionList() == null ||
                                songsEntity.getAuditionList().size() == 0 ||
                                songsEntity.getAuditionList().size() == 1) {
                            Toast.makeText(SongListDetailActivity.this, "暂无资源", Toast.LENGTH_LONG).show();
                        } else if (songsEntity.getAuditionList().size() > 1) {

                            String download_url = songsEntity.getAuditionList().get(1).getUrl();
                            Log.i("download_url", songsEntity.getUrlList().get(0).getUrl());
                            startDownloadService(index, download_url, songsEntity.getName(), songsEntity.getSingerName());

                            index++;
                            pw.dismiss();
                        }
                        break;
                    case R.id.layout_song_share:
                        url = songsEntity.getUrlList().get(0).getUrl();
                        mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
                        //是否只有已登录用户才能打开分享选择页
                        mController.openShare(SongListDetailActivity.this, false);
                        QQShare();
                        break;
                }

            }
        }, rankingListBackground);
        pw.showAtLocation(findViewById(R.id.coordinator_layout), Gravity.CENTER, 0, 0);
    }

    private void startDownloadService(int notifyId, String url, String songName, String singerName) {     //绑定服务类
        Intent intent = new Intent(SongListDetailActivity.this, DownloadServices.class);
        intent.putExtra("url", url);
        intent.putExtra("singerName", singerName);
        intent.putExtra("songName", songName);
        intent.putExtra("notifyId", notifyId);
        startService(intent);
    }

}
